package com.tools.module.base.service.impl;

import com.tools.common.dynamicquery.DynamicQuery;
import com.tools.common.model.PageBean;
import com.tools.common.model.Result;
import com.tools.common.util.DateUtils;
import com.tools.common.util.ShiroUtils;
import com.tools.module.base.repository.BaseClassifyRepository;
import com.tools.module.base.entity.BaseClassify;
import com.tools.module.base.service.BaseClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BaseClassifyServiceImpl implements BaseClassifyService {

    @Autowired
    private DynamicQuery dynamicQuery;
    @Autowired
    private BaseClassifyRepository classifyRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(BaseClassify classify) {
        classify.setUpdateTime(DateUtils.getTimestamp());
        classifyRepository.saveAndFlush(classify);
        return Result.ok("保存成功");
    }

    @Override
    public Result get(Long id) {
        BaseClassify classify = classifyRepository.getOne(id);
        return Result.ok(classify);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result delete(Long id) {
        classifyRepository.deleteById(id);
        return Result.ok("删除成功");
    }

    @Override
    public Result list(BaseClassify classify) {
        String nativeSql = "SELECT COUNT(*) FROM base_classify";
        Long count = dynamicQuery.nativeQueryCount(nativeSql);
        PageBean<BaseClassify> data = new PageBean<>();
        if(count>0){
            nativeSql = "SELECT * FROM base_classify ORDER BY id desc";
            Pageable pageable = PageRequest.of(classify.getPageNo(),classify.getPageSize());
            List<BaseClassify> list =  dynamicQuery.nativeQueryPagingList(BaseClassify.class,pageable,nativeSql);
            data = new PageBean(list,count);
        }
        return Result.ok(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateSeq(BaseClassify classify) {
        String nativeSql = "update base_classify set seq = seq +1 where seq >= ?";
        dynamicQuery.nativeExecuteUpdate(nativeSql,classify.getSeq());
        return Result.ok("修改成功");
    }

    @Override
    public Long queryBySeq(BaseClassify classify) {
        String nativeSql = "SELECT COUNT(*) FROM base_classify where   seq = "+classify.getSeq();
        Long count = dynamicQuery.nativeQueryCount(nativeSql);
        return count;
    }
}
